#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions

cluster="smart-update"
create_namespace $namespace
deploy_operator

kubectl_bin apply -f $conf_dir/secrets.yml -f $conf_dir/client.yml

IMAGE_MONGOD_TO_UPDATE=${IMAGE_MONGOD}
if [[ "${IMAGE_MONGOD}" == *"percona-server-mongodb-operator"* ]]; then
    MONGO_VER=$(echo -n "${IMAGE_MONGOD}" | $sed -r 's/.*([0-9].[0-9])$/\1/')
else
    MONGO_VER=$(echo -n "${IMAGE_MONGOD}" | $sed -r 's/.*:([0-9]+\.[0-9]+).*$/\1/')
fi
IMAGE_MONGOD="percona:psmdb-$MONGO_VER"

desc 'create first PSMDB cluster'
spinup_psmdb ${cluster}-rs0 $test_dir/conf/${cluster}-rs0.yml
compare_kubectl "statefulset/${cluster}-rs0"
sleep 10

initial_primary=$(get_mongo_primary "clusterAdmin:clusterAdmin123456@$cluster-rs0.$namespace" "$cluster")
pods=($(kubectl get pods -l app.kubernetes.io/name=percona-server-mongodb -o=name | sed 's/pod\///g' | sed "s/$initial_primary//g" | sort -r))

kubectl_bin patch psmdb "${cluster}" --type=merge --patch '{ "spec": { "image": "'"$IMAGE_MONGOD_TO_UPDATE"'" }}'

for pod in "${pods[@]}"; do
    echo "wait for $pod update"
    sleep 10
    wait_pod "$pod"
    img=$(kubectl get pod/$pod -o jsonpath='{.spec.containers[0].image}')
    if [ "$img" != "$IMAGE_MONGOD_TO_UPDATE" ]; then
        echo "image was not updated"
        exit 1
    fi
done

desc "check primary should have old image"
img=$(kubectl get pod/$initial_primary -o jsonpath='{.spec.containers[0].image}')
if [ "$img" != "$IMAGE_MONGOD" ]; then
    echo "image should be old on primary pod at that moment"
    exit 1
fi

desc "wait for primary $initial_primary update"
sleep 10
wait_pod "$initial_primary"
img=$(kubectl get pod/$initial_primary -o jsonpath='{.spec.containers[0].image}')
if [ "$img" != "$IMAGE_MONGOD_TO_UPDATE" ]; then
    echo "image was not updated"
    exit 1
fi

restarted_pods=($(kubectl get pods -l app.kubernetes.io/name=percona-server-mongodb -o=name --sort-by=.status.startTime | sed 's/pod\///g'))
pods+=("$initial_primary")

for i in "${!pods[@]}"; do
    if [ "${pods[i]}" != "${restarted_pods[i]}" ]; then
        echo "pod ${pods[i]} is not equal to pod ${restarted_pods[i]}"
        exit 1
    fi
done

destroy $namespace
